package com.crm.system.controller.systemManager;

import com.alibaba.fastjson.JSONObject;
import com.crm.common.model.DataResponse;
import com.crm.common.model.DhResponse;
import com.crm.common.model.Enum.ResponseCodeEnum;
import com.crm.common.util.PathUtil;
import com.crm.model.vo.systemManager.CallImportVO;
import com.crm.system.service.cluePoolManager.ExcelUtil;
import com.crm.system.service.systemManager.CallImportService;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.ArrayList;
import java.util.List;

/**
 * 呼叫信息导入相关接口
 * @Author renshaorong
 * @Date 2021/4/22
 */
@RestController
@RequestMapping("/callImport")
@Slf4j
public class CallImportController {

    @Autowired
    private CallImportService callImportService;

    /**
     * 导入功能
     * @param request
     * @param file
     * @return
     */
    @PostMapping("/callImport")
    public DataResponse callImport(HttpServletRequest request,
                                   @RequestParam MultipartFile file) throws IOException {
        JSONObject jsonObject = new JSONObject();
        try {
            ExcelUtil excelUtil = new ExcelUtil();
            List<CallImportVO> list = excelUtil.excelImport(file.getInputStream(), CallImportVO.class);//1.读取前端的excel文件并转换成list集合
            if (list == null || list.size() == 0) {
                return new DhResponse(ResponseCodeEnum.ERROR.getResponseCode());
            }
            jsonObject = callImportService.importCall(list);

        } catch (Exception e) {
            log.error("callImport error:", e);
        }
        //返回导入数量、重复数量
        return new DhResponse(ResponseCodeEnum.OK.getResponseCode(),jsonObject);
    }

    /**
     * 单条录入功能
     * @param request
     * @param callImportVO
     * @return
     */
    @PostMapping("/addCall")
    public DataResponse addCall(HttpServletRequest request,
                                   @RequestParam CallImportVO callImportVO) throws IOException {
        List<CallImportVO> list = new ArrayList<>();
        list.add(callImportVO);
        return new DhResponse(ResponseCodeEnum.OK.getResponseCode(),callImportService.importCall(list));
    }

    /**
     * 下载模版
     * @param response
     */
    @GetMapping("/downloadCallTemplate")
    public void downloadTemplate(HttpServletResponse response) {
        InputStream fis = null;
        OutputStream os = null;
        String path = "";
        try {
            String fileName="call.xlsx";
            //根据系统来判断取相对路径还是绝对路径
            String osName = System.getProperty("os.name");
            if (osName.toLowerCase().startsWith("win")) {
                path = Thread.currentThread().getContextClassLoader().getResource("").getPath() + PathUtil.getDownPath() + "call.xlsx";
            } else {
                path = PathUtil.getDownPath() + "call.xlsx";
            }

            fileName = new java.net.URLDecoder().decode(fileName, "utf-8");
            response.setContentType("application/octet-stream;charset=UTF-8");
            response.setHeader("Content-Disposition", "attachment;filename=" + new String(fileName.getBytes("UTF-8"), "iso8859-1"));
            //以流的形式下载文件
            fis = new BufferedInputStream(new FileInputStream(path));
            XSSFWorkbook xssfWorkbook = new XSSFWorkbook(fis);
            os = new BufferedOutputStream(response.getOutputStream());
            xssfWorkbook.write(os);
            os.flush();
        } catch (Exception e) {
            log.error("downloadCallTemplate error:", e);
        } finally {
            if(fis != null){
                try {
                    fis.close();
                } catch (IOException e1) {
                    log.error("downloadCallTemplate error:", e1);
                }
            }
            if(os != null){
                try {
                    os.close();
                } catch (IOException e2) {
                    log.error("downloadCallTemplate error:", e2);
                }
            }
        }
    }
}
